#include "features2d-test.h"

using namespace std;  
using namespace cv; 




int colorBreak(){

	maderfaker::ImgShower im;

	Mat input,bHist, gHist, rHist ;
	int histSize = 256, histWidth = 1024, histHeight = 800;
	int pixelsForColor = cvRound((double) histWidth / histSize);
	float range []  = {0, 256};
	const float * histRange = range;
	vector<Mat> bgrPlanes;
	ofstream outFile;
	

	input = imread(IMG_COLOR_BREAK_SMALL);
	cout << "input channels " << input.channels() << endl;
	
	split(input, bgrPlanes);
	cout << "splitted size " << bgrPlanes.size() << endl;
	
	calcHist(&bgrPlanes[0], 1, 0, Mat(), bHist, 1, &histSize, &histRange, true, false);
	calcHist(&bgrPlanes[1], 1, 0, Mat(), gHist, 1, &histSize, &histRange, true, false);
	calcHist(&bgrPlanes[2], 1, 0, Mat(), rHist, 1, &histSize, &histRange, true, false);
	cout << "bHist size " << bHist.size() << endl;

	outFile.open(THIS_DIR + string("colorBreak-hist.txt"), ios_base::out | ios_base::in);
	if(outFile.is_open()){
		outFile.close();
		outFile.open(THIS_DIR + string("colorBreak-hist.txt"),ios_base::out | ios_base::app);
	}
	else{
		outFile.open(THIS_DIR + string("colorBreak-hist.txt"),ios_base::out);
	}

		/*
		outFile << "before noralize" << endl;
		for(int i=0;i<bHist.rows;i++){
			outFile << bHist.at<float>(i) <<"\t";
		}
		outFile << endl;
		double min=0, max=0;
		int minIdx =-1, maxIdx = -1;
		minMaxIdx(bHist,&min, &max,&minIdx, &maxIdx);
		outFile << "min " <<min<< "\tmax " <<max<<"\tminIdx " <<minIdx<<"\tmaxIdx " <<maxIdx<< endl;
	*/

	Mat histImage(histHeight, histWidth, CV_8UC3, Scalar(0,0,0));

	normalize(bHist, bHist, 0,histImage.rows, NORM_MINMAX, -1, Mat());
	normalize(gHist, gHist, 0,histImage.rows, NORM_MINMAX, -1, Mat());
	normalize(rHist, rHist, 0,histImage.rows, NORM_MINMAX, -1, Mat());

		/*
		outFile << "after noralize" << endl;
		for(int i=0;i<bHist.rows;i++){
			outFile << bHist.at<float>(i) <<"\t";
		}
		outFile << endl;
		minMaxIdx(bHist,&min, &max,&minIdx, &maxIdx);
		outFile << "min " <<min<< "\tmax " <<max<<"\tminIdx " <<minIdx<<"\tmaxIdx " <<maxIdx<< endl;
	
		outFile.close();
		*/
	
	for(int i=1;i<histSize;i++){
		line(histImage
			,Point( pixelsForColor * (i-1), histHeight - cvRound( bHist.at<float>(i-1)))
			,Point( pixelsForColor * (i),	histHeight - cvRound( bHist.at<float>(i)))
			,Scalar(255,0,0),2,8,0);
		line(histImage
			,Point( pixelsForColor * (i-1), histHeight - cvRound( gHist.at<float>(i-1)))
			,Point( pixelsForColor * (i),	histHeight - cvRound( gHist.at<float>(i)))
			,Scalar(0,255,0),2,8,0);
		line(histImage
			,Point( pixelsForColor * (i-1), histHeight - cvRound( rHist.at<float>(i-1)))
			,Point( pixelsForColor * (i),	histHeight - cvRound( rHist.at<float>(i)))
			,Scalar(0,0,255),2,8,0);
			
	}

	


	im.sh("HIST",histImage);
	
	
	return 0;
}